// TODO: Move winmain.cpp to RuntimeEnvironment.

#include "application.h"
#include "bcmi_enventities.h"
#include <bcm/bcm.h>
#include <windows.h>
#include <tchar.h>

#ifndef NDEBUG
#include <cstdio>

bool createDebugConsoleWindow()
{
	if (!AllocConsole())
		return false;
	// Reopen file handles for stdin, stdout and sterr to point to
	// the newly created console
	freopen("CONIN$",  "r", stdin);
	freopen("CONOUT$", "w", stdout);
	freopen("CONOUT$", "w", stderr);
	std::cout << "DEBUG console has been created!" << std::endl;
	return true;
}
#endif // NDEBUG

//extern "C"
int WINAPI _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR lpszArgument,
                     int nCmdShow)
{
#ifndef NDEBUG
	createDebugConsoleWindow();
#endif // NDEBUG
	bcm::ComponentManager &compMgr = bcm::ComponentManager::instance();
	switch (compMgr.loadComponent(TEXT("rte.dll"))) {
	case bcm::LC_NODLL:
		MessageBox(NULL, TEXT("Could not load rte.dll."),
			TEXT("Critical Error"), MB_OK);
		return 1;
	case bcm::LC_NOCOMPONENT:
		MessageBox(NULL, TEXT("No component contained in rte.dll."),
			TEXT("Critical Error"), MB_OK);
		return 1;
	case bcm::LC_ALREADYUSED:
		MessageBox(NULL, TEXT("Component \"rte\" already registered."),
			TEXT("Critical Error"), MB_OK);
		return 1;
	case bcm::LC_OK:
#ifndef NDEBUG
		MessageBox(NULL, TEXT("Component \"rte\" properly loaded from rte.dll."),
			TEXT("FYI"), MB_OK);
#endif // NDEBUG
		break;
	}
	bcm::Component *component;
	switch (compMgr.getComponent("rte", &component)) {
	case bcm::GC_UNREGISTERED:
		MessageBox(NULL, TEXT("Component \"rte\" was never registered."),
			TEXT("Critical Error"), MB_OK);
		return 1;
	case bcm::GC_NOCOMPONENT:
		MessageBox(NULL, TEXT("Component \"rte\" not available in DLL."),
			TEXT("Critical Error"), MB_OK);
		return 1;
	case bcm::GC_INCOMPLETE:
		MessageBox(NULL, TEXT("Component \"rte\" incomplete."),
			TEXT("Critical Error"), MB_OK);
		return 1;
	case bcm::GC_OK:
#ifndef NDEBUG
		MessageBox(NULL, TEXT("Component \"rte\" properly loaded."),
			TEXT("FYI"), MB_OK);
#endif // NDEBUG
		break;
	}
	bcm::Interface *iface;
	iface = component->getInterface("enventities");
	if (iface == 0) {
		MessageBox(NULL, TEXT("Could not get interface Environment Entities."),
			TEXT("Critical Error"), MB_OK);
		return 1;
	}
	cnc::rtl::BCMI_EnvironmentEntities *env = dynamic_cast<cnc::rtl::BCMI_EnvironmentEntities *>(iface);
	if (env == 0) {
		MessageBox(NULL, TEXT("Retrieved interface is not Environment Entities."),
			TEXT("Critical Error"), MB_OK);
		return 1;
	}
	env->setupEnvironment(hInstance, hPrevInstance, lpszArgument, nCmdShow);
	cnc::rtl::Application *application = cnc::rtl::getApplication();
	if (application != 0)
		return application->main();
	return 0;
}

